#ifndef BASE_MODUL_H
#define BASE_MODUL_H
#include <QFile>
#include <QtCore> 
#include <QTextCodec>
#include <QCoreApplication>
#include "main.h"



#include <QDomDocument>
#include <QtDebug>
#include <QDebug> 
#include <QSettings>
#include <QDomDocument>
#include <QDomElement>
#include <QDomImplementation>
#include <QDomProcessingInstruction>
#include <QFile>
#include <QTextCodec>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QCalendarWidget>
#include <QtGui/QDialog>


//
/*  Save file as base_modul.h  */
/*  incomming class name Base_Modul */
//
//
class Base_Modul
{

//
public: 
Base_Modul()
{
 Load_Connector();
}



QString TimeaGo( int ms , int sek )
{
    QString elapstime;
    QString elapettime,ssec,smin,shor,speeder;
    int sec_el;
    
    if (ms > 0) {
    sec_el = ms / 1000;
    }
    
    if (sek > 0) {
    sec_el = sek;
    }
    
    if (ms < 1 && sek < 1) {
    return elapstime;
    }
    
    
    
       int min_el = 0;
   int hor_el = 0;
   int timebreak = 0;
   for (int i = 0; i < sec_el; ++i)  {
       timebreak++;
       if (timebreak == 60) {
           timebreak = 0;
           min_el++;           
       }
       if (min_el == 60) {
          min_el = 0;
          hor_el++;           
       }
       if (hor_el == 24) {
           hor_el = 0;
           /* day 1 */         
       }
       
   }
   
   if (timebreak < 10) {
   ssec = QString("0%1").arg(timebreak);  
   } else {
   ssec = QString("%1").arg(timebreak);   
   }
   if (min_el < 10) {
   smin = QString("0%1").arg(min_el);  
   } else {
   smin = QString("%1").arg(min_el);   
   }
   if (hor_el < 10) {
   shor = QString("0%1").arg(hor_el);  
   } else {
   shor = QString("%1").arg(hor_el);   
   }
    
   elapstime = QString("%1:%2:%3").arg(shor).arg(smin).arg(ssec);
   return elapstime;
}





QString  BiteorMega( int peso  )
{
    QString humanread;
    double canno = peso / 1024;
    int sale = canno;
    if (peso > 0) {
        if (canno < 1) {
           sale = 1; 
        }
    }
    
   if (sale < 1025) {
   humanread = QString("KB:%1").arg(sale);
   return humanread;
   }
   
   float megad = sale / 1024;
   
   if (megad < 1025) {
   humanread = QString("MB:%1").arg(megad);
   return humanread;
   } else {
   humanread = QString("GB:1+"); 
   }
   
return humanread;
}



QString  PathNameTree( QString sname )
{
    if (sname.endsWith("/")) {
    sname = sname.mid(0,sname.size() - 1);
    }
    
    QStringList list;
    list = sname.split("/");
    int doves = list.size();
    QString smallname = list.at( doves - 1 );
    
return smallname;
}



QString  PeelEnding( QString name )
{
    name = name.mid(1,name.size() - 2);
    
return name;
}

/* grep nummer on [77] */
QString  Firstupper( QString nametomake )
{
    QString firtupper,lower,fullname,na,nb;
    int xse = nametomake.size();
    na = nametomake.toLower();
    nb = nametomake.toUpper();
    firtupper = nb.left(1);
    fullname = QString("%1%2").arg(firtupper).arg(na.mid(1,xse - 1));
    
return fullname;
}

bool  image_extension( QString nametomake )
{
    bool fanny = false;
    QString na;
    na = nametomake.toLower();
    if ( na.endsWith(".png") or na.endsWith(".jpeg") or na.endsWith(".jpg") or na.endsWith(".gif") ) {
     fanny = true;   
    }
return fanny;
}

bool file_put_contents_append(QString fullFileName,QString xml)
{
    QString data = xml+"\n";
    QFile f( fullFileName );
	if ( f.open( QFile::Append | QFile::Text ) )
	{
		QTextStream sw( &f );
		sw << data;
		f.close();
		return true;
	}
	return false;
    
}




QString DesktopFile( QString fullFileName )
{
#if defined Q_WS_MAC
return fullFileName;
#endif
#if defined Q_WS_X11
return fullFileName;
#endif
    
    if (fullFileName.startsWith("http://", Qt::CaseInsensitive) or 
        fullFileName.startsWith("https://", Qt::CaseInsensitive) or
        fullFileName.startsWith("ftp://", Qt::CaseInsensitive) or
        fullFileName.startsWith("news://", Qt::CaseInsensitive) or
        fullFileName.startsWith("mailto:", Qt::CaseInsensitive) or
        fullFileName.startsWith("webdav://", Qt::CaseInsensitive)  )
       { 
         return fullFileName;
       } else {
         return fullFileName.prepend("file:///");  
       }
       
       
}



/* encode to url strings */
QString EncodeUrlPart( QString xml  )
{
    QUrl urlmod(QString("http://localhost/%1").arg(xml));
    QByteArray capsed(urlmod.toEncoded());
    QString res = QString("%1").arg(capsed.data());
    res = res.replace("%20","_");
    res = res.replace("%","");
    QUrl urlmod2(res);
    res = urlmod2.path ();
    res = res.replace("/","");
    return res;
}

uint DavTimeStringCreated( QString indate )
{
    /* incomming format "2007-02-07T18:44:24Z" */
           indate.resize(indate.size() - 1);
	       QStringList sdate = indate.split("T");
           if (sdate.size() != 2) {
           return QTime_Null();
           }
           QString reformat = sdate.join(" ");
           //////qDebug() << "date  converted " << reformat;
           QDateTime dateTime2 = QDateTime::fromString(reformat,"yyyy-MM-dd HH:mm:ss");
	    dateTime2.setTimeSpec(Qt::UTC);
           QDateTime dateTime3 = dateTime2.toLocalTime();
    return dateTime3.toTime_t();
}

uint MailTimeString( QString indate )
{
    /* incomming format Wed, 07 Feb 2007 18:44:19 GMT*/
    /* or mail rtf Date format! http://www.faqs.org/rfcs/rfc788.html */
    indate.replace("Date:","");
    indate.trimmed();
    QStringList sdate = indate.split(" ");
    if (sdate.size() != 6) {
    return QTime_Null();
    }
    sdate.removeFirst();
    sdate.removeLast();
    QString reformat = sdate.join(" ");
    QDateTime dateTime2 = QDateTime::fromString(reformat,"dd MMM yyyy HH:mm:ss");
    dateTime2.setTimeSpec(Qt::UTC);
    QDateTime dateTime3 = dateTime2.toLocalTime();
    return dateTime3.toTime_t();
}
/* time null unix time long nummer */
uint QTime_Null()
{
    QDateTime timer1( QDateTime::currentDateTime() ); 
    return timer1.toTime_t();
}

/* display a mail date format  UmanTimeFromUnix(QTime_Null())   */
QString UmanTimeFromUnix( uint unixtime )
{
     /* mail rtf Date format! http://www.faqs.org/rfcs/rfc788.html */
     QDateTime fromunix;
     fromunix.setTime_t(unixtime); 
     QStringList RTFdays = QStringList() << "day_NULL" << "Mon" << "Tue" << "Wed" << "Thu" << "Fri" << "Sat" << "Sun";
     QStringList RTFmonth = QStringList() << "month_NULL" << "Jan" << "Feb" << "Mar" << "Apr" << "May" << "Jun" << "Jul" << "Aug" << "Sep" << "Oct" << "Nov" << "Dec";
     QDate timeroad(dateswap("yyyy",unixtime),dateswap("M",unixtime),dateswap("d",unixtime));
     /*qDebug() << "### RTFdays " << RTFdays.at(timeroad.dayOfWeek());
     qDebug() << "### RTFmonth " << RTFmonth.at(dateswap("M",unixtime));
     qDebug() << "### yyyy " << dateswap("yyyy",unixtime);
     qDebug() << "### M " << dateswap("M",unixtime);
     qDebug() << "### d " << dateswap("d",unixtime);*/
     QStringList rtfd_line;
     rtfd_line.clear();
     rtfd_line.append("Date: ");
     rtfd_line.append(RTFdays.at(timeroad.dayOfWeek()));
     rtfd_line.append(", ");
     rtfd_line.append(QString::number(dateswap("d",unixtime)));
     rtfd_line.append(" ");
     rtfd_line.append(RTFmonth.at(dateswap("M",unixtime)));
     rtfd_line.append(" ");
     rtfd_line.append(QString::number(dateswap("yyyy",unixtime)));
     rtfd_line.append(" ");
     rtfd_line.append(fromunix.toString("hh:mm:ss"));
     rtfd_line.append("");
     /*qDebug() << "### mail rtf Date format " << rtfd_line.join("");*/
return QString(rtfd_line.join(""));
}





/* display a mail date format  UmanTimeFromUnix(QTime_Null())   */
QString UmanTimeFromUnix2( uint unixtime )
{
     QDateTime fromunix;
     fromunix.setTime_t(unixtime); 
     QStringList RTFdays = QStringList() << "day_NULL" << "Mon" << "Tue" << "Wed" << "Thu" << "Fri" << "Sat" << "Sun";
     QStringList RTFmonth = QStringList() << "month_NULL" << "Jan" << "Feb" << "Mar" << "Apr" << "May" << "Jun" << "Jul" << "Aug" << "Sep" << "Oct" << "Nov" << "Dec";
     QDate timeroad(dateswap("yyyy",unixtime),dateswap("M",unixtime),dateswap("d",unixtime));
     QStringList rtfd_line;
     rtfd_line.clear();
     rtfd_line.append(RTFdays.at(timeroad.dayOfWeek()));
     rtfd_line.append(", ");
     rtfd_line.append(QString::number(dateswap("d",unixtime)));
     rtfd_line.append(" ");
     rtfd_line.append(RTFmonth.at(dateswap("M",unixtime)));
     rtfd_line.append(" ");
     rtfd_line.append(QString::number(dateswap("yyyy",unixtime)));
     rtfd_line.append(" ");
     rtfd_line.append(fromunix.toString("hh:mm:ss"));
     rtfd_line.append("");
return QString(rtfd_line.join(""));
}


/* date format to stirng */
QString datetr(QString form, uint unixtime )
{
     QDateTime fromunix;
     fromunix.setTime_t(unixtime); 
     return fromunix.toString((const QString)form);
}
/* take a qstring and put to double */
double direct_double(QString xid)
{
    double newnummer = 0.01;
    if (is_numeric(xid)) {
        bool ok; 
        newnummer = xid.toDouble(&ok);
        return newnummer;
    }
 return newnummer;
}

/* take a qstring and put to int */
int direct_int(QString xid)
{
    int newnummer = 0;
    if (is_numeric(xid)) {
        bool ok; 
        newnummer = xid.toInt(&ok);
        return newnummer;
    }
 return newnummer;
}

/* return int value from a unixtime date MMM YYY ... */
int dateswap(QString form, uint unixtime )
{
     QDateTime fromunix;
     fromunix.setTime_t(unixtime); 
     QString numeric = fromunix.toString((const QString)form);
     bool ok; 
     return (int)numeric.toFloat(&ok);
}


/* check if a int or float nummer */
bool is_numeric(QString incomming)
{
    incomming.replace(QString(" "), QString("")); /* trimm */
    QString str2 = incomming;
    bool ok; 
    str2.toFloat(&ok); 
return ok;
}


QString CDDirUp( QString path )
{
     /* linux cd..  */
    if (path == "/") {
     return path;
    }
    QStringList list;
    list = path.split("/");
    QStringList fdir;
    int totaldir = list.size() - 2; 
    ////////qDebug() << "#### cd .. ->" << totaldir << "-" << list.size() << "-" << list;
    fdir.clear();
    for (int i = 0; i < totaldir; ++i)  {
        fdir.append(list.at(i));
     }
    QString dircdup5 = fdir.join("/");
    dircdup5.prepend("/");
    dircdup5.append("/");
    return CheckSlash(dircdup5);
}


/*
      for(int i=xx.size()-1; i>=0;i--){
        doSomething(xx.at(i));
      } 
*/


QStringList OOOOOUReverseList( QStringList xx  )
{
    if (xx.size() == 0) {
        return xx;
    }
    QStringList newreversed;
     newreversed.clear();
       bool walking = true;
       int o = xx.size();
         for (;walking;) {
             o--;    /*  size 1 goto 0  ;  size 2 start on 1 end on 0 */
             newreversed.append(xx.at(o));
             if (o == 0) {
               walking = false;  
             }
         }
  return newreversed;    
}


 QStringList ReverseList(const QStringList &list)
{
    QStringList reversedList = list;
    QStringList::iterator __first = reversedList.begin();
    QStringList::iterator __last = reversedList.end();
    {
        while (true)
            if (__first == __last || __first == --__last)
                return reversedList;
            else
            {
                qSwap(*__first, *__last);
                ++__first;
            }
    }
    
}








QString CheckSlash( QString path )
{
    if (path == "/") {
     return path;
    }
    QString cleanpath;
    if (!path.startsWith("/")) {
        path = path.prepend("/");
     }
    if (!path.endsWith("/")) {
       path = path.append("/");
    }
    cleanpath = path;
    cleanpath = cleanpath.replace("//","/");
    return cleanpath;
}


/* encode to name */
QString encodeBase64( QString xml )
{
    QByteArray text;
    text.append(xml);
    return text.toBase64();
}

/* decode to name */
QString decodeBase64( QString xml )
{
    QByteArray xcode("");;
    xcode.append(xml);
    QByteArray precode(QByteArray::fromBase64(xcode));
    QString notetxt = precode.data();
    return notetxt;
}
/* extract domaine from a url */
QString Domain( QString url )
{
   QString hdomain = "";
   QUrl wurl( url );
   hdomain = QString( "http://%1/" ).arg( wurl.host() );
   return hdomain;
}
/* return a config setting from a xml file */
QString  Global_Config_Base( QString tagname , QString filename )
{
    QFile xmlfile(filename);
    QString isis="";
    if(!xmlfile.open( QIODevice::ReadOnly ) ) {
    return isis;
    }
    QString errorStr, obname, inhalt;
    int errorLine;
    int errorColumn;
    
    QDomDocument doc("http://www.pulitzer.ch/2005/PuliCMS/1.0"); 
     if (!doc.setContent(&xmlfile,true, &errorStr, &errorLine, &errorColumn)) {
     return isis;
     xmlfile.close();
     } 
    QDomElement root = doc.documentElement();
    if( root.tagName() != "setting" ) {
    return isis;
    }
    QDomNode n = root.firstChild();
    while( !n.isNull() )
    {
        QDomElement e = n.toElement();
        if( !e.isNull() )
        {
                   if( e.tagName() == tagname ) {
                   xmlfile.close();
                   return decodeBase64(e.text());
                   }
                   
         n = n.nextSibling();
        } 
    }
xmlfile.close();
return isis;
}

/* read the contenet of a local file as qstring */
QString fopenutf8(QString fullFileName)
{
    QString inside = "";
    QFile file(fullFileName); 
    if (file.exists()) {
                if (file.open(QFile::ReadOnly | QFile::Text)) {
                    inside = QString::fromUtf8(file.readAll());
                  file.close();
                }
    }

return inside;
}


/* read the contenet of a local file as qstring */
QString fopeniso(QString fullFileName)
{
    QString inside = "";
    QFile file(fullFileName); 
    if (file.exists()) {
                if (file.open(QFile::ReadOnly | QFile::Text)) {
                    inside =file.readAll();   
                  file.close();
                }
    }

return inside;
}

/* write a file to utf-8 format */
bool fwriteutf8(QString fullFileName,QString xml)
{
    if (fullFileName.contains("/", Qt::CaseInsensitive)) {
    QString ultimacartellaaperta = fullFileName.left(fullFileName.lastIndexOf("/"))+"/";
    QDir dira(ultimacartellaaperta);
    if ( dira.mkpath(ultimacartellaaperta) ) { } else {
    return false;
    }
    }
    
        QTextCodec *codecx;
        codecx = QTextCodec::codecForMib(106);
        QFile f( fullFileName );
        if ( f.open( QFile::WriteOnly | QFile::Text ) )
        {
        QTextStream sw( &f );
        sw.setCodec(codecx);
        sw << xml;
        f.close();
        return true;
        }
        return false;
}

/* write a file to iso format */
bool fwriteiso(QString fullFileName,QString xml)
{
    
    if (fullFileName.contains("/", Qt::CaseInsensitive)) {
    
    QString ultimacartellaaperta = fullFileName.left(fullFileName.lastIndexOf("/"))+"/";
    QDir dira(ultimacartellaaperta);
    if ( dira.mkpath(ultimacartellaaperta) ) { } else {
    return false;
    }
    
    }
    
    
        QTextCodec *codecx;
        codecx = QTextCodec::codecForMib(4);
        QFile f( fullFileName );
        if ( f.open( QFile::WriteOnly | QFile::Text ) )
        {
        QTextStream sw( &f );
        sw.setCodec(codecx);
        sw << xml;
        f.close();
        return true;
        }
        return false;
}


/* check if a file exist alert dons say true if a zero byte file!  */
bool is_file(QString fullFileName)
{
    if (!fullFileName.size() > 0) {
      return false;  
    }
    QDir diro(fullFileName);
       if (diro.exists()) {
         return false;   
       }
    QFile f( fullFileName );
	if ( f.exists(fullFileName) ) {
    return true;  
	} else {
	return false;
    }
}

/* remove a file */
bool qt_unlink(QString fullFileName)
{
    if (fullFileName.size() > 0) {
    QFile f( fullFileName );
	if ( f.exists(fullFileName) ) {
       if (f.remove()) {
        return true;
       }
	}
    }
return false;
}

/* copy file from a to b ... if dir not exist make it ...*/
bool Copy_To(QString inputfile, QString outfile)
{
    bool actioncpy = false;
    QString ultimacartellaaperta = outfile.left(outfile.lastIndexOf("/"))+"/";
    QDir dira(ultimacartellaaperta);
    if ( dira.mkpath(ultimacartellaaperta) ) { } else {
    return actioncpy;
    }
    if (is_file(inputfile)) {
           qt_unlink(outfile);
           QFile Imaged(inputfile); 
               if (Imaged.copy(outfile)) {
                   actioncpy = true; 
                }
    }
return actioncpy;
}




/* quote and dequote sql s result */
QString sql_Quote( QString xml )
{
   //the following checks are necessary before exporting
  //strings to XML. see http://hdf.ncsa.uiuc.edu/HDF5/XML/xml_escape_chars.html for details
   QString text = xml;
   text.replace("\"","\\\"");  /* 228 ``*/
   text.replace("'","`");
   return text;
}

QString sql_DeQuote( QString xml )
{
   //the following checks are necessary before exporting
  //strings to XML. see http://hdf.ncsa.uiuc.edu/HDF5/XML/xml_escape_chars.html for details
  QString text = xml;
   text.replace("\\\"","\"");  /* 228 ``*/
   text.replace("`","\'");
  return text;
}


QString FileNameFix( QString xml )
{
   //the following checks are necessary before exporting
  //strings to XML. see http://hdf.ncsa.uiuc.edu/HDF5/XML/xml_escape_chars.html for details
  QString text = xml;
   text.replace("\\\"","");  /* 228 ``*/
   text.replace("`","");
   text.replace(" ","_");
  return text;
}





/* decode url from cookie or other */
QString  Url_Decode( QString indata )
{
/*
http://www.blooberry.com/indexdot/html/topics/urlencoding.htm
Dollar ("$")  24 
Ampersand ("&") 26
Plus ("+") 2B
Comma (",")  2C
Forward slash/Virgule ("/") 2F
Colon (":")  3A
Semi-colon (";") 3B
Equals ("=") 3D
Question mark ("?") 3F
'At' symbol ("@")  40
Left Curly Brace ("{")  7B
Right Curly Brace ("}") 7D
Vertical Bar/Pipe ("|") 7C
Backslash ("\") 5C
Caret ("^") 5E
Tilde ("~") 7E
Left Square Bracket ("[") 5B
Right Square Bracket ("]") 5D
Grave Accent ("`")  60
*/
QString blnull = "";
QString notaccept = "%60|%5D|%5B|%7E|%5E|%5C|%7C|%7D|%7B";
QStringList notallow;
            notallow = notaccept.split("|");

             for (int i = 0; i < notallow.size(); ++i) {
                 if ( indata.contains(notallow.at(i)) ) {
                   return blnull;   
                 } 
             }
  
         QString spaceout = indata.replace("%20"," ");
                 spaceout = spaceout.replace("%3A",":");  
                 spaceout = spaceout.replace("%3B",";");
                 spaceout = spaceout.replace("%3D","=");
                 spaceout = spaceout.replace("%2F","/");
                 spaceout = spaceout.replace("%3F","?");
                 spaceout = spaceout.replace("%40","@");
                 spaceout = spaceout.replace("%24","$");
                 spaceout = spaceout.replace("%2B","+");
                 spaceout = spaceout.replace("+"," ");  
                 int zool = spaceout.indexOf(";",0);
         return spaceout.left(zool);;
}


/* grep nummer on [77] */
int  BraketNummer( QString braket )
{
    int esanummer = 0;
    if (braket.startsWith("[")) {
       braket.replace(QString("["), QString("")); 
       int zool = braket.indexOf("]",0); 
           if (zool > 0) {
              QString   xid = braket.left(zool);  
               if (is_numeric(xid)) {
                      bool ok; 
                      esanummer = xid.toInt(&ok);
               }
           }
    }
return esanummer;
}

/* remove dir recursive */
void DownDir_RM(const QString d)
{
   QDir dir(d);
   if (dir.exists())
   {
      const QFileInfoList list = dir.entryInfoList();
      QFileInfo fi;
      for (int l = 0; l < list.size(); l++)
      {
         fi = list.at(l);
         if (fi.isDir() && fi.fileName() != "." && fi.fileName() != "..")
            DownDir_RM(fi.absoluteFilePath());
         else if (fi.isFile())
         {
            bool ret = qt_unlink(fi.absoluteFilePath());
                  if (!ret) {
                   //////Api_Log("Can't remove: " + fi.absoluteFilePath() + " (write-protect?)");
		  }
         } 
        
      }
      dir.rmdir(d);
      
   }
} 

/* simple md5 to found diffs */
QString myMd5( QString xml )
{
    QString str = xml;
    str.resize(38);
    QString upperd = str.toUpper();
    QByteArray text;
    text.append(upperd);
    QString parse = text.toBase64();
    parse.resize(12);
    QString md7 = parse;
    return md7;
}
void ResetDir()
{
    QDir::setCurrent(currentdir); 
}
protected:
private:
   QString currentdir;
 void Load_Connector()
{
currentdir = QDir::currentPath();   /* remember current path on start! */
}
signals:
public slots:

};
//
#endif // BASE_MODUL_H

